import cloud from '@lafjs/cloud'
const db = cloud.mongo.db
let dbName = "invoicing"
let userId

export default async function (ctx: FunctionContext) {
  if (cloud.utils.isString(ctx.user.uid)) {
    userId = ctx.user.uid
  } else {
    userId = ctx.user.uid._id
  }

  switch (ctx.body.type) {
    case "list":
      return getRecord(ctx.body.data)
      break;
    case "del"://删除
      return recordDel(ctx.body.data)
      break;
    case "clearAll":
      return clearAll()
    case "query":
      return query(ctx.body.data)
      break;
    default:
      break;
  }
}

async function query(info) {
  let query = { ...info }
  delete query.pageIndex
  delete query.pageSize
  delete query.type
  delete query.year

  let whereJson = cloud.utils.extractValidKeys(query)
  whereJson = cloud.utils.fuzzyQuery({ ...whereJson })
  if (info.type && info.type == "admin") {

  } else {
    whereJson.invoiceUser = userId
  }

  //如果有时间筛选
  if (info.year) {
    const startOfYear = new Date(info.year, 0, 1).getTime(); // 该年份的开始时间戳
    const endOfYear = new Date(info.year, 11, 31, 23, 59, 59, 999).getTime(); // 该年份的结束时间戳
    whereJson["_add_time"] = { $gt: startOfYear, $lt: endOfYear }
  }
  const data = await db.collection(dbName).find(whereJson).toArray()
  return cloud.utils.requestReturn({ data })
}

async function clearAll() {
  await db.collection(dbName).deleteMany({})
  return cloud.utils.requestReturn({ data: "清空完成" })
}


let getRecord = async (info) => {
  let query = { ...info }
  delete query.pageIndex
  delete query.pageSize
  delete query.type
  delete query.year

  let whereJson = cloud.utils.extractValidKeys(query)
  whereJson = cloud.utils.fuzzyQuery({ ...whereJson })
  if (info.type && info.type == "admin") {

  } else {
    whereJson.invoiceUser = userId
  }

  //如果有时间筛选
  if (info.year) {
    const startOfYear = new Date(info.year, 0, 1).getTime(); // 该年份的开始时间戳
    const endOfYear = new Date(info.year, 11, 31, 23, 59, 59, 999).getTime(); // 该年份的结束时间戳
    whereJson["_add_time"] = { $gt: startOfYear, $lt: endOfYear }
  }

  let res = await cloud.nw.db.selects({
    dbName,
    getCount: true,
    pageIndex: info.pageIndex,
    pageSize: info.pageSize,
    whereJson,
    sortArr: [{ "name": "_add_time", "type": "desc" }],
    // 副表列表
    foreignDB: [
      {
        dbName: "web-users",//副表 order
        localKey: "invoiceUser",
        foreignKey: "_id",
        as: "invoiceUser_info",
        limit: 1,
        // 副表字段显示规则
        fieldJson: { mobile: 1 },
      },
      {
        dbName: "web-order",//副表 order
        localKey: "ddlsh",
        foreignKey: "out_trade_no",
        as: "curriculum_info",
        limit: 1,
        // 副表字段显示规则
        fieldJson: { curriculum_id: 1 },
      },
    ]
  });
  return cloud.utils.requestReturn({ data: res })
}

let recordDel = async (data) => {
  await cloud.nw.db.del({
    dbName, whereJson: { _id: data }
  });
  return cloud.utils.requestReturn({ data: "" })
}